<?php

namespace app\mp\controller;

use app\common\entity\BackResult;
use app\common\entity\Result;
use app\common\service\VideoAndTopicService;
use app\common\model\Category as CategoryModel;
use app\Request;
use app\common\service\CategoryService;
use app\wxapp\service\WechatUserService;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/4 0004
 * Time: 19:51
 */
class Category extends Base
{
    //取出所有的分类目录
    public function all()
    {
        $service = new CategoryService();
        $data = $service->all();
        return Result::success($data);
    }

    /**
     * 前台分类
     * @param CategoryService $category
     * @return \think\Response
     */
    public function tree(CategoryService $category)
    {
        return Result::success($category->tree());
    }

    /**
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(Request $request)
    {
        $id = $request->param('id');
        if ($id && ($cate = CategoryModel::find($id))) {
            return Result::success($cate);
        } else {
            return BackResult::error(null, '分类数据不存在');
        }
    }

    /**
     * 用户已经设置的选中状态 目前初始状态 为全部选中
     */
    public function selected()
    {
        $service = new WechatUserService();
        $res = $service->getSelectedCategory($this->user['id']);
        return Result::success($res);
    }

    /**
     * 偏好设置
     * @param Request $request
     * @return \think\Response
     */
    public function select(Request $request)
    {
        $data = $request->post();
        $service = new WechatUserService();
        $service->saveSelectedCategory($data, $this->user);
        return Result::success([]);
    }


    /**
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function videoAndTopic(Request $request)
    {
        $ids = $request->param('ids', null);
        $page = (int)$request->param('page', 1);
        $size = (int)$request->param('size', 10);
        $service = new VideoAndTopicService();
        $result = [];
        foreach ($ids as $id) {
            $result[$id] = $service->select([
                'page' => $page,
                'size' => $size,
                'category' => $id,
                'order' => 'hot'
            ]);
        }
        return Result::success($result);
    }
}
